# 创建集合
fruits = {'apple', 'banana', 'orange'}
colors = set(['red', 'green', 'blue'])  # 从列表创建

# 基本操作
print('apple' in fruits)  # True 检查成员
fruits.add('pear')       # 添加元素
fruits.remove('banana')  # 移除元素，不存在会报错
fruits.discard('mango')  # 安全移除，不存在不会报错

# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}

print(a | b)  # 并集 {1, 2, 3, 4, 5, 6}
print(a & b)  # 交集 {3, 4}
print(a - b)  # 差集(a有b无) {1, 2}
print(a ^ b)  # 对称差集(仅在a或b中) {1, 2, 5, 6}

# 集合推导式
squares = {x**2 for x in range(10) if x%2 == 0}
print(squares)  # {0, 4, 16, 36, 64}











stack = []
stack.append('A')  # 入栈
stack.append('B')
stack.append('C')

print(stack.pop())  # 'C' 出栈(LIFO后进先出)
print(stack.pop())  # 'B'





from collections import deque

queue = deque()
queue.append('A')  # 入队
queue.append('B')
queue.append('C')

print(queue.popleft())  # 'A' 出队(FIFO先进先出)
print(queue.popleft())  # 'B'





from collections import Counter

words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)

print(word_counts)  # Counter({'apple': 3, 'banana': 2, 'orange': 1})
print(word_counts.most_common(2))  # [('apple', 3), ('banana', 2)]

# 更新计数器
word_counts.update(['apple', 'pear'])
print(word_counts['apple'])  # 4








from collections import defaultdict

# 值默认为int(0)
fruit_counts = defaultdict(int)
fruit_counts['apple'] += 1  # 不需要初始化

# 值默认为list
students = defaultdict(list)
students['class1'].append('Alice')
students['class1'].append('Bob')

print(fruit_counts)  # defaultdict(<class 'int'>, {'apple': 1})
print(students)      # defaultdict(<class 'list'>, {'class1': ['Alice', 'Bob']})







from collections import namedtuple

# 创建Point类
Point = namedtuple('Point', ['x', 'y'])
p = Point(10, y=20)

print(p.x, p.y)  # 10 20
print(p[0], p[1])  # 也支持索引访问


def is_balanced(expr):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}

    for char in expr:
        if char in mapping.values():  # 左括号入栈
            stack.append(char)
        elif char in mapping.keys():  # 右括号检查
            if not stack or stack.pop() != mapping[char]:
                return False
    return not stack  # 栈空则平衡


print(is_balanced("({[]})"))  # True
print(is_balanced("({[}])"))  # False








from collections import Counter
import re

text = "Python is an interpreted, high-level, general-purpose programming language."
words = re.findall(r'\w+', text.lower())  # 提取单词

word_counts = Counter(words)
print(word_counts.most_common(3))
# 输出: [('python', 1), ('is', 1), ('an', 1)]


from collections import deque


def max_sliding_window(nums, k):
    q = deque()
    result = []

    for i, num in enumerate(nums):
        while q and nums[q[-1]] <= num:
            q.pop()  # 移除较小的元素
        q.append(i)

        if q[0] == i - k:  # 移除窗口外的元素
            q.popleft()

        if i >= k - 1:
            result.append(nums[q[0]])

    return result


print(max_sliding_window([1, 3, -1, -3, 5, 3, 6, 7], 3))  # [3,3,5,5,6,7]












# 列表去重
numbers = [1, 2, 2, 3, 4, 4, 5]
unique_numbers = list(set(numbers))
print(unique_numbers)  # 输出可能是 [1, 2, 3, 4, 5] (集合无序)

# 字符串去重
text = "hello world"
unique_chars = ''.join(set(text))
print(unique_chars)  # 输出类似 "helo wrd" (顺序不保留)

# 字典列表去重(基于特定键)
data = [
    {'id': 1, 'name': 'Alice'},
    {'id': 2, 'name': 'Bob'},
    {'id': 1, 'name': 'Alice'},
    {'id': 3, 'name': 'Charlie'}
]

# 方法1: 使用集合和元组
unique_data = {tuple(item.items()) for item in data}
unique_data = [dict(item) for item in unique_data]
print(unique_data)
# 输出: [{'id': 1, 'name': 'Alice'}, {'id': 2, 'name': 'Bob'}, {'id': 3, 'name': 'Charlie'}]

# 方法2: 使用id键去重
seen_ids = set()
unique_by_id = []
for item in data:
    if item['id'] not in seen_ids:
        seen_ids.add(item['id'])
        unique_by_id.append(item)
print(unique_by_id)






from collections import OrderedDict

# 保留首次出现的顺序
numbers = [3, 1, 2, 1, 4, 3, 5]
unique_ordered = list(OrderedDict.fromkeys(numbers))
print(unique_ordered)  # [3, 1, 2, 4, 5]

# 或者使用Python 3.7+的字典特性(字典保持插入顺序)
unique_ordered = list(dict.fromkeys(numbers))


def is_balanced(expr):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}

    for char in expr:
        if char in mapping.values():  # 左括号入栈
            stack.append(char)
        elif char in mapping.keys():  # 右括号检查匹配
            if not stack or stack.pop() != mapping[char]:
                return False
    return not stack  # 栈空则所有括号都匹配


# 测试用例
print(is_balanced("()"))  # True
print(is_balanced("()[]{}"))  # True
print(is_balanced("(]"))  # False
print(is_balanced("([)]"))  # False
print(is_balanced("{[]}"))  # True
print(is_balanced(""))  # True (空字符串)
print(is_balanced("(("))  # False (栈未空)


def check_brackets(expr):
    stack = []
    mapping = {')': '(', '}': '{', ']': '['}

    for i, char in enumerate(expr):
        if char in mapping.values():  # 左括号
            stack.append((char, i))  # 存储字符和位置
        elif char in mapping.keys():  # 右括号
            if not stack:
                return f"Unmatched '{char}' at position {i}"
            last, pos = stack.pop()
            if last != mapping[char]:
                return f"Mismatch: '{last}' at {pos} and '{char}' at {i}"

    if stack:
        last, pos = stack.pop()
        return f"Unmatched '{last}' at position {pos}"
    return "All brackets are balanced"


print(check_brackets("(a + b} * [c - d)"))
# 输出: Mismatch: '(' at 0 and '}' at 6


def is_nested_balanced(expr):
    stack = []
    opening = '([{<'
    closing = ')]}>'
    mapping = dict(zip(closing, opening))

    for char in expr:
        if char in opening:
            stack.append(char)
        elif char in closing:
            if not stack or stack.pop() != mapping[char]:
                return False
    return not stack


print(is_nested_balanced("<[{()}]>"))  # True
print(is_nested_balanced("<[)]>"))  # False

import re


def is_html_balanced(html):
    stack = []
    tags = re.findall(r'<(/?\w+)>', html)  # 匹配所有标签

    for tag in tags:
        if not tag.startswith('/'):  # 开始标签
            stack.append(tag)
        else:  # 结束标签
            if not stack:
                return False
            if stack.pop() != tag[1:]:  # 去除'/'
                return False
    return not stack


html1 = "<html><body><p>Hello</p></body></html>"
html2 = "<div><p>Error</div></p>"
print(is_html_balanced(html1))  # True
print(is_html_balanced(html2))  # False












def deep_deduplicate(data):
    if isinstance(data, dict):
        # 字典去重：先对值去重，再转为可哈希的元组
        return {k: deep_deduplicate(v) for k, v in data.items()}
    elif isinstance(data, (list, tuple)):
        # 列表/元组去重：递归处理元素后转为元组去重
        seen = set()
        unique = []
        for item in data:
            item = deep_deduplicate(item)
            item_tuple = tuple(item.items()) if isinstance(item, dict) else item
            if item_tuple not in seen:
                seen.add(item_tuple)
                unique.append(item)
        return unique if isinstance(data, list) else tuple(unique)
    return data

nested_data = [
    {'id': 1, 'tags': ['a', 'b', 'a']},
    {'id': 2, 'tags': ['b', 'c']},
    {'id': 1, 'tags': ['a', 'b', 'a']},
    ['x', 'y', 'x']
]
print(deep_deduplicate(nested_data))
# 输出: [{'id': 1, 'tags': ['a', 'b']}, {'id': 2, 'tags': ['b', 'c']}, ['x', 'y']]